<template>
  <div class="container">
    <el-alert
      type="warning"
      class="mb20"
      :closable="false"
    >
      <p>如果已有提交答案，请确保修改问题后，不会修改到原有答案，</p>
      <p>题目操作（上移，下移，删除）后，请点击“保存”按钮，保存结果</p>
    </el-alert>

    <div class="text-center mb20">
      <el-button
        type="primary"
        plain
        size="medium"
        @click="addSingleQuestion"
      >添加单选题</el-button>
      <el-button
        type="success"
        plain
        size="medium"
        @click="addMultipleQuestion"
      >添加多选题</el-button>
      <el-button
        type="info"
        plain
        size="medium"
        @click="addRateQuestion"
      >添加数值题</el-button>
    </div>

    <el-card
      v-for="(item, index) in questions"
      :key="item.key"
      class="box-card questions-card"
    >
      <div slot="header" class="card-header clearfix">
        <h5 class="title pull-left">
          <span v-if="item.type === 'single'" class="text-primary">单选题</span>
          <span v-else-if="item.type === 'multiple'" class="text-success">多选题</span>
          <span v-else class="text-info">数值题</span>
        </h5>
        <div class="pull-right">
          <el-button
            type="text"
            icon="el-icon-top"
            size="small"
            class="btn pull-left"
            @click="upQuestion(item)"
          >上移</el-button>
          <el-button
            type="text"
            icon="el-icon-bottom"
            size="small"
            class="btn pull-left"
            @click="downQuestion(item)"
          >下移</el-button>
          <el-button
            type="text"
            icon="el-icon-delete"
            size="small"
            class="btn pull-left"
            @click="removeQuestion(item)"
          >删除</el-button>
        </div>
      </div>

      <div class="card-wrapper">
        <el-form label-position="right" label-width="140px" class="questions-form">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="题目标题">
                <el-input v-model="item.headline" size="medium" placeholder="请输入题目标题" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="副标题或提示">
                <el-input v-model="item.subheading" size="medium" placeholder="请输入副标题或提示" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="item.type === 'multiple'" :gutter="20">
            <el-col :span="24">
              <el-form-item label="可选选项个数">
                <el-input-number
                  v-model="item.optionCount"
                  :min="0"
                  :max="10"
                  size="medium"
                />
                <span class="text-warning">（0为不限制个数）</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="item.type === 'rate'" :gutter="20">
            <el-col :span="8">
              <el-form-item label="最小值">
                <el-input-number
                  v-model="item.value.min"
                  size="medium"
                  :min="0"
                  :max="10"
                  :step="1"
                  placeholder="请输入最小值"
                  style="max-width: 100%;"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="最大值">
                <el-input-number
                  v-model="item.value.max"
                  size="medium"
                  :min="0"
                  :max="10"
                  :step="1"
                  placeholder="请输入最大值"
                  style="max-width: 100%;"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="步长">
                <el-input-number
                  v-model="item.value.step"
                  size="medium"
                  :min="0.5"
                  :max="1"
                  :step="0.5"
                  placeholder="请输入步长"
                  style="max-width: 100%;"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-else :gutter="20">
            <el-col :span="20">
              <el-form-item label="编辑选项">
                <el-row
                  v-for="(option, idx) in item.checkOptions"
                  :key="idx"
                  class="option-item"
                >
                  <el-col :span="18">
                    <el-input v-model="option.value" size="medium" placeholder="请输入选项内容">
                      <template slot="prepend">{{ getIndexLetter(idx + 1) }}</template>
                      <el-button
                        v-if="showRemoveOptionBtn(item.type, item.checkOptions)"
                        slot="append"
                        icon="el-icon-close"
                        @click="removeOption(index, option)"
                      />
                    </el-input>
                  </el-col>

                  <el-col :span="6" class="pl20">
                    <el-switch
                      v-model="option.openText"
                      active-text="开放文本"
                      :active-value="1"
                      :inactive-value="0"
                    />
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-button
                icon="el-icon-plus"
                size="medium"
                @click="addOptions(index)"
              >添加选项</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-card>

    <div v-if="questions.length > 0" class="text-center mt20">
      <el-button @click="pageBack">返 回</el-button>
      <el-button
        type="primary"
        @click="submitQuestions"
      >保 存</el-button>
    </div>
  </div>
</template>

<script>
import {
  getSurveysQuestions,
  addSurveysQuestions
} from '@/api/surveys'
import {
  indexToLetters
} from '@/utils'

export default {
  name: 'SurveysQuestions',
  data() {
    return {
      surveyId: '',
      questions: [],
      loading: false
    }
  },
  watch: {
    $route: {
      handler(route) {
        this.surveyId = route.params && route.params.id
      },
      immediate: true
    }
  },
  created() {
    this.surveyId = this.$route.params.id
    this.fetchData()
  },
  methods: {
    fetchData() {
      getSurveysQuestions({
        id: this.surveyId
      }).then(response => {
        // console.log(response)
        const { data } = response
        this.questions = data
      }).catch(err => {
        console.log(err)
      })
    },
    addSingleQuestion() {
      this.questions.push({
        id: this.surveyId,
        type: 'single',
        typeText: '单选题',
        headline: '',
        subheading: '',
        checkOptions: [{
          value: '',
          openText: 0
        }],
        key: Date.now()
      })
    },
    addMultipleQuestion() {
      this.questions.push({
        id: this.surveyId,
        type: 'multiple',
        typeText: '多选题',
        headline: '',
        subheading: '',
        optionCount: 0,
        checkOptions: [{
          value: '',
          openText: 0
        }, {
          value: '',
          openText: 0
        }],
        key: Date.now()
      })
    },
    addRateQuestion() {
      this.questions.push({
        id: this.surveyId,
        type: 'rate',
        typeText: '数值题',
        headline: '',
        subheading: '',
        value: {
          min: 0,
          max: 5,
          step: 1
        },
        key: Date.now()
      })
    },
    upQuestion(item) {
      const index = this.questions.indexOf(item)
      if (index === 0) {
        return
      }
      this.questions[index - 1] = this.questions.splice(index, 1, this.questions[index - 1])[0]
    },
    downQuestion(item) {
      const index = this.questions.indexOf(item)
      if (index === this.questions.length - 1) {
        return
      }
      this.questions[index + 1] = this.questions.splice(index, 1, this.questions[index + 1])[0]
    },
    removeQuestion(item) {
      this.$confirm('确认删除此题目?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = this.questions.indexOf(item)
        if (index !== -1) {
          this.questions.splice(index, 1)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    addOptions(index) {
      this.questions[index].checkOptions.push({
        value: '',
        openText: 0
      })
    },
    removeOption(index, item) {
      const idx = this.questions[index].checkOptions.indexOf(item)
      if (idx !== -1) {
        this.questions[index].checkOptions.splice(idx, 1)
      }
    },
    showRemoveOptionBtn(type, options) {
      return (type === 'multiple' && options.length > 2) || (type === 'single' && options.length > 1)
    },
    getIndexLetter(idx) {
      return indexToLetters(idx)
    },
    submitQuestions() {
      console.log(this.questions)
      this.questions.forEach(item => {
        if (!this._.isEmpty(item.checkOptions) && !this._.isNil(item.checkOptions)) {
          item.options = []
          item.checkOptions.forEach(option => {
            item.options.push(option.value)
          })
          item.options = item.options.join('|')
          item.checkOptionsStr = JSON.stringify(item.checkOptions)
        }
      })
      this.loading = true
      addSurveysQuestions(this.questions).then(response => {
        // console.log(response)
        this.$notify({
          title: '成功',
          message: '题目设置成功',
          type: 'success',
          duration: 2000
        })
        this.loading = false
      }).catch(err => {
        console.log(err)
      })
    },
    pageBack() {
      this.$router.go(-1)
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  padding: 40px 140px;
}
.questions-card {
  .card-wrapper {
    line-height: 36px;
  }
  .el-form-item {
    margin-bottom: auto;
    /deep/ .el-form-item__label,
    /deep/ .el-form-item__content {
      line-height: 36px;
    }
  }
  & + .questions-card {
    margin-top: 20px;
  }
  .el-row {
    margin-bottom: 12px;
    &:last-child {
      margin-bottom: 0;
    }
  }
  .option-item {
    margin-bottom: 6px;
    /deep/ .el-input-group__prepend {
      width: 60px;
      text-align: center;
    }
    &:last-child {
      margin-bottom: 0;
    }
  }
}
</style>
